﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO.Compression;

/// <summary>
/// Summary description for HttpCompressionModule
/// </summary>
public class HttpCompressionModule : IHttpModule
{
    public HttpCompressionModule()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    #region IHttpModule Members

    public void Dispose()
    {
        
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        if (app.Request.Browser.IsBrowser("IE"))
            if (app.Request.Browser.MajorVersion < 7)
                return;
        if (app.Request.Path.Contains(".png") || app.Request.Path.Contains(".jpg") || app.Request.Path.Contains(".gif"))
            return;
        if (app.Request.Path.Contains(".aspx"))
        {
            if (IsEncodingAccepted("gzip"))
            {
                app.Response.Filter = new GZipStream(app.Response.Filter, CompressionMode.Compress);
                SetEncoding("gzip");
            }
            else if (IsEncodingAccepted("deflate"))
            {
                app.Response.Filter = new DeflateStream(app.Response.Filter, CompressionMode.Compress);
                SetEncoding("deflate");
            }
        }
    }

    private bool IsEncodingAccepted(string encoding)
    {
        return HttpContext.Current.Request.Headers["Accept-encoding"] != null &&
            HttpContext.Current.Request.Headers["Accept-encoding"].Contains(encoding);
    }

    private void SetEncoding(string encoding)
    {
        HttpContext.Current.Response.AppendHeader("Content-encoding", encoding);
    }

    #endregion
}
